package com.iocup.keybastion.authorize.parser;


import com.iocup.keybastion.authorize.element.AnnotationAuthElementProvider;
import com.iocup.keybastion.authorize.element.AuthElement;
import org.apache.commons.lang3.StringUtils;

import java.lang.annotation.Annotation;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * @author xyjxust
 * @create 2022/3/3 9:31
 **/
public class DefaultAuthAnnotationParser implements AuthAnnotationParser {

    private AnnotationAuthElementProvider authElementProvider = new AnnotationAuthElementProvider();


    private Map<Class,AuthAnnoObject> authAnnoObjectMap = new HashMap<>();


    @Override
    public void parser(String key, AuthAnnoObject authAnnoObject, Annotation annotation) {
        doParser(key,authAnnoObject,annotation);
    }

    @Override
    public AnnotationAuthElementProvider getAuthElementProvider() {
        return authElementProvider;
    }

    @Override
    public AuthAnnotationParser addAuthAnnoObject(AuthAnnoObject... authAnnoObjects) {
        Arrays.asList(authAnnoObjects).forEach(a->{
            authAnnoObjectMap.put(a.getAnnClass(),a);
        });
        return this;
    }

    @Override
    public AuthAnnoObject getAuthAnnoObject(Class<? extends Annotation> clazz) {
        return authAnnoObjectMap.get(clazz);
    }


    private void doParser(String key, AuthAnnoObject authAnnoObject,Annotation annotation) {
        if(StringUtils.isBlank(key)||authAnnoObject==null|| annotation==null){
            return;
        }
        AuthElement authElement = authAnnoObject.getElementParser().parser(key,
                annotation);
        if (authElement != null) {
            authElementProvider.getElementStore().put(authElement);
        }
    }



}
